package servlet.DeviceServlet;

import dao.DeviceDao;
import entity.DeviceBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myUtil.deviceCheck;

import java.io.IOException;

@WebServlet("/deviceSave")
public class DeviceSaveServlet extends HttpServlet {
    public DeviceSaveServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String number = req.getParameter("number");
        String type = req.getParameter("type");
        String vendor = req.getParameter("vendor");
        String date = req.getParameter("date");
        String time = req.getParameter("time");
        String afterSales = req.getParameter("afterSales");
        String phone = req.getParameter("phone");
        String illustrate = req.getParameter("illustrate");

        DeviceBean device = new DeviceBean();
        device.setName(name);
        device.setNumber(number);
        device.setType(type);
        device.setVendor(vendor);
        device.setDate(date);
        device.setTime(time);
        device.setAfterSales(afterSales);
        device.setPhone(phone);
        device.setIllustrate(illustrate);

        if (deviceCheck.checkS(name, 9) && deviceCheck.checkNumber(number) && deviceCheck.checkS(type, 21) &&
                deviceCheck.checkS(vendor, 21) && deviceCheck.checkS(date, 21) && deviceCheck.checkTime(time) &&
                deviceCheck.checkS(afterSales, 9) && deviceCheck.checkPhone(phone)) {


            DeviceDao dao = new DeviceDao();
            if (id == null || id == "" || id.equals("0")) {
                dao.addDoInsertDevice(device);
            } else {
                device.setId(Integer.parseInt(id));
                dao.editDoUpdateDevice(device);
            }

            resp.sendRedirect("deviceList");
        } else {
            req.setAttribute("device", device);
            req.getRequestDispatcher("device_edit.jsp").forward(req, resp);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
